package com.zjq.authoritysystem.config.security;


import com.zjq.authoritysystem.config.security.handler.AnonymousAuthenticationHandler;
import com.zjq.authoritysystem.config.security.handler.CustomerAccessDeniedHandler;
import com.zjq.authoritysystem.config.security.handler.LoginFailureHandler;
import com.zjq.authoritysystem.config.security.handler.LoginSuccessHandler;
import com.zjq.authoritysystem.config.security.sevice.CustomerUserDetailsService;
import com.zjq.authoritysystem.filter.CheckTokenFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * @author Kimiaaaaa
 * @className SecurityConfig
 * @Description
 * @date 2023-09-19 15:53
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private LoginSuccessHandler loginSuccessHandler;

    @Resource
    private LoginFailureHandler loginFailureHandler;

    @Resource
    private CustomerAccessDeniedHandler customerAccessDeniedHandler;

    @Resource
    private AnonymousAuthenticationHandler anonymousAuthenticationHandler;

    @Resource
    private CustomerUserDetailsService customerUserDetailsService;

    @Resource
    private CheckTokenFilter checkTokenFilter;

    /**
     * 注入加密类
     *
     * @return 加密类对象
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 放行白名单
     */
    private static final String[] WHITE_LIST = {
            "/api/user/login",
            "/api/pub/oss/upload",
            "/favicon.ico",
            "/doc.html",
            "/doc.html/**",
            "/webjars/**",
            "/swagger-ui.html",
            "/swagger-ui.html/**",
            "/swagger-resources",
            "/swagger-resources/**",
            "/v2/**",
            "/v3/**"
    };


    /**
     * 处理登录认证
     *
     * @param http security安全配置对象
     * @throws Exception 错误信息
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //登录前进行过滤
        http.addFilterBefore(checkTokenFilter, UsernamePasswordAuthenticationFilter.class);

        //登录过程处理
        http.formLogin()
                .loginProcessingUrl("/api/user/login") // 登录请求url地址，自定义即可
                .successHandler(loginSuccessHandler) // 登录成功处理器
                .failureHandler(loginFailureHandler) // 登录失败处理器
                //.usernameParameter("username")  // 如果前端登录表单不是username则需要在这里定义
                .and()
                .csrf().disable() // 关闭CSRF保护
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)  //禁用session
                .and()
                .authorizeRequests()  //设置需要拦截的请求
                .antMatchers(WHITE_LIST).permitAll() // 放行请求（白名单）
                .anyRequest().authenticated() // 其他请求一律需要身份验证
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(anonymousAuthenticationHandler) // 匿名用户无权访问处理器
                .accessDeniedHandler(customerAccessDeniedHandler)  // 认证用户无权限访问处理器
                .and()
                .cors();   // 开启跨域请求
    }

    /**
     * 配置认证处理器
     *
     * @param auth 构建身份验证核心接口（AuthenticationManager）配置对象
     * @throws Exception 错误信息
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customerUserDetailsService).passwordEncoder(passwordEncoder());
    }


}
